<template>
	<view class="classlist">
		<!-- 长度大于0或者没有数据 -->
		<view v-if="!classList.length && !noData" class="loadingLayout">
			<uni-load-more status="loading"></uni-load-more>
		</view>
		
		<view class="content">
			<navigator :url="`/pages/preview/preview?id=${item._id}`" class="item" v-for="item in classList" :key="item._id">
				<image :src="item.smallPicurl" mode="aspectFill"></image>
			</navigator>
		</view>
		
		<view v-if="classList.length || noData" class="loadingLayout">
			<uni-load-more :status="noData?'noMore':'loading'"></uni-load-more>
		</view>
		<view class="safe-area-inset-bottom"></view>
	</view>
</template>

<script setup>
import { ref } from 'vue'
import { onLoad, onUnload, onReachBottom, onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app'
import { apiGetClassList, apiGetHistoryList } from '@/api/apis.js'
import { gotoHome } from '@/utils/common.js'

const classList = ref([]) // 分类列表数据
const noData = ref(false) // 判断还有没有数据，触底加载使用

const queryParams = {
	pageNum: 1,
	pageSize: 12
}
let pageName
onLoad((e) => {
	// console.log(e)
	const { id=null, name=null, type=null } = e
	if (type) queryParams.type = type
	if (id) queryParams.classid = id
	// 如果id不存在，返回首页
	// if (!id) return gotoHome()
	pageName = name
	// console.log(queryParams)
	// console.log(id, name)
	uni.setNavigationBarTitle({
		title: name
	})
	// 函数要在这里执行，setup执行时机是最早的，如果在setup中调用，此时还没执行onLoad
	getClassList()
})
// console.log(queryParams)

// 离开分类列表页面后，清除缓存
onUnload(() => {
	uni.removeStorageSync('storageClassList')
})

// 触底加载更多
onReachBottom(() => {
	if (noData.value) return
	// console.log(123)
	queryParams.pageNum++
	getClassList()
})

// 获取分类列表数据
const getClassList = async () => {
	let res = []
	if (queryParams.classid) res = await apiGetClassList(queryParams)
	if (queryParams.type) res = await apiGetHistoryList(queryParams)
	// 这是为了 onReachBottom 触底加载更多
	classList.value = [...classList.value, ...res.data]
	if (res.data.length < queryParams.pageSize)
		noData.value = true
	// console.log(res)
	// 把获取的数据缓存到storage中，要放大看时把small.webp改成.jpg
	uni.setStorageSync('storageClassList', classList.value)
	// console.log(classList.value)
}

// 分享给好友
onShareAppMessage((e) => {
	// console.log(e)
	return {
		title: '咸虾米壁纸-'+pageName, // 标题
		path: `pages/classlist/classlist?id=${queryParams.classid}&name=${pageName}` // 点击分享到哪个页面
	}
})

// 分享到朋友圈
onShareTimeline(() => {
	return {
		title: '咸虾米壁纸-'+pageName, // 标题
		// imageUrl: '/static/images/logo2.jpg' // 分享的链接的图片
		query: `id=${queryParams.classid}&name=${pageName}`
	}
})
</script>

<style lang="scss" scoped>
.classlist {
	.content {
		display: grid;
		grid-template-columns: repeat(3, 1fr);
		gap: 5rpx;
		padding: 5rpx;
		.item {
			height: 440rpx;
			image {
				display: block;
				width: 100%;
				height: 100%;
			}
		}
	}
}
</style>
